#include "config.h"

static DEBUG_LEVEL g_debug_level = DEBUG_LEVEL_DEBUG;
DEBUG_LEVEL GetDebugLevel() {
	return g_debug_level;
}

void SetDebugLevel (DEBUG_LEVEL debug_level) {
	g_debug_level = debug_level;
}

static FILE* debug_output_file = NULL;
void DebugOutput( enum DEBUG_LEVEL level, const char* fmt, ... )
{
	char buf[1024];
	va_list ap;

	// check if need to print
	if( level < g_debug_level ) return;

	// prepare string to output
	va_start( ap, fmt );
#ifdef _WIN32
	vsnprintf_s( buf, sizeof(buf), sizeof(buf)-1, fmt, ap );
#else
	vsnprintf( buf, sizeof(buf), fmt, ap );
#endif

	// do output
	if( debug_output_file )
	{
		fprintf( debug_output_file, "%s\n", buf );
		fflush( debug_output_file );
	}
	else printf( "%s\n", buf );

	va_end( ap );
}

void DebugOutputWithPrefix( enum DEBUG_LEVEL level, const char* prefix, const char* fmt, ... )
{
	char buf[1024];
	va_list ap;

	// check if need to print
	if( level < g_debug_level ) return;

	// prepare string to output
	va_start( ap, fmt );
#ifdef _WIN32
	vsnprintf_s( buf, sizeof(buf), sizeof(buf)-1, fmt, ap );
#else
	vsnprintf( buf, sizeof(buf), fmt, ap );
#endif

	// do output
	if( debug_output_file )
	{
		fprintf( debug_output_file, "%s: %s\n", prefix, buf );
		fflush( debug_output_file );
	}
	else printf( "%s: %s\n", prefix, buf );

	va_end( ap );
}

void SetDebugOutputFile( const char* filename )
{
	if( debug_output_file != NULL ) fclose( debug_output_file );
	debug_output_file = fopen( filename, "w" );
}

void PolarSSLDebugCallback( void *ctx, int level, const char *str )
{
	if( level < 1 )	DebugOutput( DEBUG_LEVEL_DEBUG, "polarssl: %s", str );
}
